<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Table, TableColumn } from '@/components/Table'
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema } from '@/components/Form'
import { ElMessageBox, ElMessage } from 'element-plus'
import { BaseButton } from '@/components/Button'
import { Icon } from '@/components/Icon'
import SetAuthDialog from './SetAuthDialog.vue'

import { ref, unref, computed, reactive } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { pick } from 'lodash-es'
import { getAddUserListApi } from '@/api/user'

// Table
const columns: TableColumn[] = [
  {
    field: 'id',
    label: '序号'
  },
  {
    field: 'name',
    label: '角色名称'
  },
  {
    field: 'description',
    label: '描述'
  },
  {
    field: 'creatorName',
    label: '创建人',
    formatter: (row) => (row.creatorName ? row.creatorName : '')
  },
  {
    field: 'createTime',
    label: '创建时间'
  },
  {
    field: 'action',
    label: '操作',
    width: 252,
    slots: {
      default: ({ row }) => {
        return row.id !== 1 ? (
          <div class="flex items-center gap-x-[10px]">
            <BaseButton type="primary" size="small" onClick={() => onOpenDialog(row)}>
              {{
                icon: () => <Icon size={20} icon="carbon:edit" />,
                default: () => '编辑'
              }}
            </BaseButton>
            <BaseButton class="!ml-0" size="small" onClick={() => openSetAuthDialog(row)}>
              设置权限
            </BaseButton>
            <BaseButton class="!ml-0" type="danger" size="small" onClick={() => onDelete(row)}>
              {{
                icon: () => <Icon size={20} icon="material-symbols:delete-outline" />,
                default: () => '删除'
              }}
            </BaseButton>
          </div>
        ) : null
      }
    }
  }
]

const { tableMethods, tableState } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const { data, count } = await getAddUserListApi({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize)
    })
    return {
      list: data,
      total: count
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { refresh } = tableMethods

// Dialog
const visible = ref(false)
const isEdit = ref(false)
const title = computed(() => (isEdit.value ? '编辑角色' : '新增角色'))

// Form
const { formRegister, formMethods } = useForm()
const { getElFormExpose, setValues, getFormData } = formMethods

const { required } = useValidator()

const schema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'description',
    label: '描述',
    component: 'Input',
    componentProps: {
      type: 'textarea'
    }
  }
])

const onOpenDialog = (row) => {
  visible.value = true
  isEdit.value = !!row
  if (row) {
    setValues(pick(row, ['id', 'name', 'description']))
  }
}

// 删除
const onDelete = (row) => {
  ElMessageBox.confirm('是否删除该角色?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await getAddUserListApi({ roleId: row.id })
      ElMessage.success('操作成功！')
      refresh()
    })
    .catch(() => {})
}

// 重置
const onReset = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.resetFields()
}

const disabled = ref(false)
// 立即提交
const onFormSubmit = async () => {
  disabled.value = true
  const formData = await getFormData()
}

const setAuthDialogRef = ref()
const openSetAuthDialog = (row) => {
  setAuthDialogRef.value.open(row.id)
}
</script>

<template>
  <ContentWrap title="角色管理">
    <template #action>
      <BaseButton type="primary" @click="onOpenDialog">
        <template #icon>
          <Icon :size="20" icon="material-symbols:add" />
        </template>
        新增
      </BaseButton>
    </template>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      :pagination="{ total: total }"
      :loading="loading"
    />

    <!-- 新增/编辑角色 弹窗 -->
    <Dialog
      v-model="visible"
      :title="title"
      width="500"
      maxHeight="500"
      :close-on-click-modal="false"
    >
      <Form
        class="w-[400px] ml-[auto] mr-[auto]"
        :schema="schema"
        :isCol="false"
        @register="formRegister"
      />
      <template #footer>
        <div class="text-center mb-[16px]">
          <BaseButton v-if="!isEdit" @click="onReset">重置</BaseButton>
          <BaseButton type="primary" debounce :disabled="disabled" @click="onFormSubmit"
            >立即提交</BaseButton
          >
        </div>
      </template>
    </Dialog>

    <!-- 设置权限 弹窗 -->
    <SetAuthDialog ref="setAuthDialogRef" />
  </ContentWrap>
</template>
